// page/diary-search-bydate/index.js
const util = require('../../util/util')
const { $Message } = require('../../dist/base/index');


const date = new Date()
const years = []
const months = []
const days = []

for (let i = 1990; i <= date.getFullYear(); i++) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  months.push(i)
}

for (let i = 1; i <= 31; i++) {
  days.push(i)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {        
    startDate: '',
    endDate: '', 
    years,
    year: date.getFullYear(),
    months,
    month: date.getMonth()+1,
    days,
    day: date.getDate(),
    value: [9999, 0, 0],
    isDaytime: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    var year_index = years.map(item => item).indexOf(that.data.year)
    var month_index = months.map(item => item).indexOf(that.data.month)
    var day_index = days.map(item => item).indexOf(that.data.day)
    //var startDate = util.formatDate(new Date())
    var startDate = that.data.startDate
    var endDate = that.data.endDate
    // 如果起始日期为空，则默认为当前日期和当前日期的前一个月
    if (startDate == '' || endDate == '') {
      startDate = util.addMonth(-1)
      endDate = util.formatDate(new Date())
    }
    
    that.setData({
      value: [year_index, month_index, day_index],
      startDate,
      endDate
    })
  },

  bindChange(e) {
    const val = e.detail.value
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]]
    })
  },
  confirm:function() {
    // console.log(this.data.day);
    var dateStr = this.data.year+"-"+this.data.month+"-"+this.data.day;
    var date = new Date(dateStr);
    console.log("pickDate",date);
    wx.setStorage({
      key: 'pickDate',
      data: date,
      success: function() {
        wx.navigateBack({
          delta: 1
        });
      }
    })
  },

  // 开始日期监听
  bindStartDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      startDate: e.detail.value,
    })
  },

  // 结束日期监听
  bindEndDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endDate: e.detail.value,
    })
  },

  date_search: function() {
    var that = this
    // 如果日期已经全部选择，则开启搜索
    var startDate = that.data.startDate
    var endDate = that.data.endDate
    if(startDate <= endDate) {
      that.setData({
        startDate,
        endDate
      })
      wx.navigateTo({
        url: '../diary-search-list/index?startDate='+startDate+'&endDate='+endDate,
      })    
    } else {
      $Message({
        content: '开始日期不得小于结束日期',
        type: 'warning',
        duration: 2
      });
    }
  },
})